package com.interfaces;

import com.common.web.CommonJspKeys;
import com.common.web.CommonKeys;
import com.common.web.Json;
import com.common.web.ReturnCodes;
import com.core.journey.JourneyJspKeys;
import com.core.journey.bo.JourneyBo;
import com.core.journey.pojo.Journey;
import com.core.user.bo.UserBo;
import com.core.user.pojo.User;
import com.core.visaInfo.VisaInfoJspKeys;
import com.core.visaInfo.bo.VisaInfoBo;
import com.core.visaInfo.dto.VisaInfoSearchCondition;
import com.core.visaInfo.pojo.VisaInfo;
import com.core.visitor.bo.VisitorBo;
import com.core.visitor.dto.VisitorSearchCondition;
import com.core.visitor.pojo.Visitor;
import com.util.DataBaseUtil;
import com.util.GsonUtil;
import com.util.exception.ComRuntimeException;
import com.util.exception.ComSystemException;
import com.util.framework.BaseController;
import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.*;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

//wbq
@Controller
public class VisaApplicationInfoController extends BaseController{
	protected Logger log = Logger.getLogger(this.getClass());
	@Resource
	private VisaInfoBo visaInfoBo;
	@Resource
	private VisitorBo visitorBo;
	@Resource
	private JourneyBo journeyBo;
	@Resource
	private UserBo userBo;
	public static String OUTPUTFILE="/Users/wbq/Desktop/export";
	public static String OUTPUTFILE2="D:\\export";  
	public static final String URL_ENTITY = "/visaInfo";
	public static final String URL_GOTO_MAIN_PAGE = URL_ENTITY
			+ "/goto_main_page";
	public static final String URL_GOTO_ADD_UPDATE_PAGE = URL_ENTITY
			+ "/goto_add_update_page";
	public static final String URL_GOTO_UPDATE_PAGE = URL_ENTITY
			+ "/goto_update_page";
	public static final String URL_ADD_UPDATE = URL_ENTITY + "/add_update";
	public static final String URL_UPDATE = URL_ENTITY + "/update";
	public static final String URL_DELETE = URL_ENTITY + "/delete";
	public static final String URL_DB = URL_ENTITY+"/database";
	public static final String URL_DB_SEARCH = URL_ENTITY+"/search";
	public static final String URL_BACK_COUNTRY = URL_ENTITY+"/gohome";
	public static final String URL_UPDATESTATE = URL_ENTITY+"/updateState";
	@RequestMapping(value=URL_DB_SEARCH,method=RequestMethod.POST,produces={"application/json;charset=utf-8"})
	@ResponseBody
	public String searchData(VisaInfoSearchCondition sc, HttpSession session){
		User userInfo =(User) session.getAttribute(CommonKeys.SESSION_USER);
		User userInfo2 =userBo.getById(userInfo);
		sc.setAddTravelId(Long.parseLong(userInfo2.getTravelAgentId()));
		String msg="";
		List<VisaInfoSearchCondition>data = visaInfoBo.searchPojoList(sc,userInfo2);
		DataBaseUtil<VisaInfoSearchCondition> db = new DataBaseUtil<VisaInfoSearchCondition>();
		int totalCount = visaInfoBo.searchCnt(sc,userInfo2);
		if (data.size()==0) {
			msg="{\"draw\":"+sc.getDraw()+",\"recordsTotal\":0,\"recordsFiltered\":0,\"data\": []}";
		}else{
			db.setTotalCount(totalCount);
			db.setRecordsFiltered(totalCount);
			db.setData(data);
			db.setDraw(sc.getDraw());
			msg = GsonUtil.gson.toJson(db);
		}
		return msg;
	}
	@RequestMapping(value=URL_GOTO_MAIN_PAGE,method=RequestMethod.GET)
	public ModelAndView gotoMainPage (HttpSession session,VisaInfoSearchCondition sc){
		User userInfo =(User) session.getAttribute(CommonKeys.SESSION_USER);
		ModelAndView modelAndView =new ModelAndView();
		modelAndView.setViewName("/visaInfo/visaInfo_main");
		modelAndView.addObject(CommonKeys.SESSION_USER,userInfo);
		return modelAndView;
	}
	@RequestMapping(value=URL_GOTO_ADD_UPDATE_PAGE,method=RequestMethod.GET)	
	public ModelAndView URL_GOTO_ADD_UPDATE_PAGE(HttpSession session) {
		User userInfo = (User) session.getAttribute(CommonKeys.SESSION_USER);
		ModelAndView modelAndView = new ModelAndView("visaInfo/visaInfo_add_update");
		modelAndView.addObject(CommonJspKeys.JspParam_SessionUserInfo, userInfo);
		return modelAndView;
	}
	@RequestMapping(value = URL_GOTO_UPDATE_PAGE, method = RequestMethod.GET)
	public ModelAndView URL_GOTO_UPDATE_PAGE(VisaInfo visaInfo,HttpSession session) {
		User userInfo = (User) session.getAttribute(CommonKeys.SESSION_USER);
		VisaInfo visaInfo2 = visaInfoBo.getById(visaInfo.getId());
		List<Journey> jouneyList =new ArrayList<Journey>();
		ModelAndView modelAndView = new ModelAndView("visaInfo/visaInfo_update");
		modelAndView.addObject(CommonJspKeys.JspParam_SessionUserInfo, userInfo);
		modelAndView.addObject(JourneyJspKeys.jspParam_JourneyList,jouneyList);
		modelAndView.addObject(VisaInfoJspKeys.JspParam_VisaInfo, visaInfo2);
		return modelAndView;
	}
//	实际add
	@ResponseBody
	@RequestMapping(value = URL_ADD_UPDATE, method = RequestMethod.POST)
	public Json add(VisaInfo visaInfo, HttpSession session) {
		Json json = new Json();
		User userInfo = (User) session.getAttribute(CommonKeys.SESSION_USER);
		User userInfo2 =userBo.getById(userInfo);
		try {
			visaInfo.setAddUserId((long)userInfo2.getId());
			visaInfo.setAddTravelId(Long.valueOf(userInfo2.getTravelAgentId()));
			visaInfo.setAddDate(new Date());
			visaInfo.setIsVisa(1);
			visaInfoBo.add(visaInfo);
			json.setNowId(visaInfo.getId());
			json.setSuccess(true);
		} catch (ComRuntimeException e) {
			json = new Json(e.getErrorCode(), e.getMessage());
		} catch (ComSystemException e) {
			log.error("error", e);
			json = new Json(e.getErrorCode(), "系统忙... " + e.getMessage());
		} catch (Throwable e) {
			log.error("error", e);
			json = new Json(ReturnCodes.SYSTEM_EXCEPTION, "系统忙... "
					+ e.getMessage());
		}
		return json;
	}
//	实际update
	@ResponseBody
	@RequestMapping(value = URL_UPDATE, method = RequestMethod.POST)
	public Json update(VisaInfo visaInfo, HttpSession session) {
		Json json = new Json();
		try {
			visaInfoBo.update(visaInfo);
			json.setSuccess(true);
		} catch (ComRuntimeException e) {
			json = new Json(e.getErrorCode(), e.getMessage());
		} catch (ComSystemException e) {
			log.error("error", e);
			json = new Json(e.getErrorCode(), "系统忙... " + e.getMessage());
		} catch (Throwable e) {
			log.error("error", e);
			json = new Json(ReturnCodes.SYSTEM_EXCEPTION, "系统忙... "
					+ e.getMessage());
		}
		return json;
	}
	@ResponseBody
	@RequestMapping(value = URL_UPDATESTATE, method = RequestMethod.POST)
	public Json UpdateState(HttpServletRequest request) {
		String items = request.getParameter("delitems");
		String afterState = request.getParameter("afterState");
	    String[] strs = items.split(",");
		Json json = new Json();
		VisaInfo tempVisaInfo =new VisaInfo();
		for (int i = 0; i < strs.length; i++) {  
			try {
				tempVisaInfo.setId(Long.parseLong(strs[i]));
				tempVisaInfo.setState(afterState);
				visaInfoBo.updateState(tempVisaInfo);
				json.setSuccess(true);
			} catch (ComRuntimeException e) {
				json = new Json(e.getErrorCode(), e.getMessage());
			} catch (ComSystemException e) {
				log.error("error", e);
				json = new Json(e.getErrorCode(), "系统忙... " + e.getMessage());
			} catch (Throwable e) {
				log.error("error", e);
				json = new Json(ReturnCodes.SYSTEM_EXCEPTION, "系统忙... "
						+ e.getMessage());
			}
		}
		return json;
	}
	@ResponseBody
	@RequestMapping(value = URL_DELETE, method = RequestMethod.POST)
	public Json delete(HttpServletRequest request) {
		String items = request.getParameter("delitems");
	    String[] strs = items.split(",");
		Json json = new Json();
		VisaInfo tempVisaInfo =new VisaInfo();
		for (int i = 0; i < strs.length; i++) {  
			try {
				tempVisaInfo.setId(Long.parseLong(strs[i]));
				visaInfoBo.del(tempVisaInfo);
				json.setSuccess(true);
			} catch (ComRuntimeException e) {
				json = new Json(e.getErrorCode(), e.getMessage());
			} catch (ComSystemException e) {
				log.error("error", e);
				json = new Json(e.getErrorCode(), "系统忙... " + e.getMessage());
			} catch (Throwable e) {
				log.error("error", e);
				json = new Json(ReturnCodes.SYSTEM_EXCEPTION, "系统忙... "
						+ e.getMessage());
			}
		}
		return json;
	}
	//归国报告书
	@ResponseBody
	@RequestMapping(value = URL_BACK_COUNTRY, method = RequestMethod.POST)
	public Json exportGoHome(HttpServletRequest request) {
		String items = request.getParameter("delitems");
	    String[] strs = items.split(",");
		Json json = new Json();
		VisaInfo tempVisaInfo =new VisaInfo();
		for (int i = 0; i < strs.length; i++) {  
			try {
				String nameString = null;
				tempVisaInfo.setId(Long.parseLong(strs[i]));
				VisitorSearchCondition tempVSC= new VisitorSearchCondition();
				tempVSC.setVisaInfoId(Long.parseLong(strs[i]));
				tempVSC.setLength(1000);
				tempVSC.setStart(0);
				List<Visitor>data = visitorBo.getVisitorList(tempVSC);
//				开始表头设置
				HSSFWorkbook workbook = new HSSFWorkbook();  
				HSSFSheet sheet = workbook.createSheet(); 
				HSSFRow row = sheet.createRow((short)0);
				row.setHeight((short)700);
				HSSFCellStyle headStyle= workbook.createCellStyle();
				String[] headers = new String[] { "氏名", "ピンイン", "性別", "居住地域", "生年月日", 
						"旅券番号", "備考"}; 
				HSSFFont font = workbook.createFont();
				font.setFontName("ＭＳ Ｐゴシック");
				headStyle.setFont(font);
				headStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
				for (int v = 0; v< headers.length; v++) { 
//					表头单元格
					HSSFCell cell = row.createCell(v); 
					HSSFRichTextString text = new HSSFRichTextString(headers[v]); 
					cell.setCellValue(text); 
					cell.setCellStyle(headStyle); 
				}
//				表内容
				for (int j=1;j<data.size()+1;j++) {
					Visitor tempVisitor =data.get(j-1);
					if (j==1) {
						nameString=tempVisitor.getName();
					}
					HSSFRow contentRow = sheet.createRow((short)j);
					contentRow.setHeight((short)500);
					HSSFCellStyle contentStyle= workbook.createCellStyle();
					HSSFFont contentfont = workbook.createFont();
					contentfont.setFontName("宋体");
					contentStyle.setFont(contentfont);
					contentStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
					HSSFCell contentCell0 = contentRow.createCell(0);
					contentCell0.setCellValue (new HSSFRichTextString(tempVisitor.getName()));
					contentCell0.setCellStyle(contentStyle);
					
					HSSFCell contentCell1 = contentRow.createCell(1);
					contentCell1.setCellValue(new HSSFRichTextString(tempVisitor.getPinyinName()));
					contentCell1.setCellStyle(contentStyle);
					
					HSSFCell contentCell2 = contentRow.createCell(2);
					contentCell2.setCellValue(new HSSFRichTextString(tempVisitor.getSex()));
					contentCell2.setCellStyle(contentStyle);
					
					HSSFCell contentCell3 = contentRow.createCell(3);
					contentCell3.setCellValue(new HSSFRichTextString(tempVisitor.getPermanentCity()));
					contentCell3.setCellStyle(contentStyle);
					
					HSSFCell contentCell4 = contentRow.createCell(4);
					SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");  
					SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy/MM/dd");
					contentCell4.setCellValue(sdf2.format(sdf.parse(tempVisitor.getBirthday())));
					contentCell4.setCellStyle(contentStyle);
					
					HSSFCell contentCell5 = contentRow.createCell(5);
					contentCell5.setCellValue(new HSSFRichTextString(tempVisitor.getPassport()));
					contentCell5.setCellStyle(contentStyle);
				}
				FileOutputStream outputStream =new FileOutputStream(OUTPUTFILE2+"/归国报告书-"+nameString+".xls");
				workbook.write(outputStream);
				outputStream.close();
			} catch (ComRuntimeException e) {
				json = new Json(e.getErrorCode(), e.getMessage());
			} catch (ComSystemException e) {
				log.error("error", e);
				json = new Json(e.getErrorCode(), "系统忙... " + e.getMessage());
			} catch (Throwable e) {
				log.error("error", e);
				json = new Json(ReturnCodes.SYSTEM_EXCEPTION, "系统忙... "
						+ e.getMessage());
			}
		}
		return json;
	}
}
